/******************** 
	作用:订单支付中心
	作者:蔡俊雄
	版本:V1.0
	时间:2015-09-04
********************/

$(function() {
	var levelTip1 = $("#category1").attr("data-tip"); //一级分类提示
	var levelTip2 = $("#category2").attr("data-tip"); //二级分类提示
	var levelTip3 = $("#category3").attr("data-tip"); //三级分类提示
	var idNotSelect = "0"; //不选分类时的ID
	var addressDataUrl = $("#addressDataUrl").val();

	//-----------------保存地址-----------------
	$("#save").on("click", function() {
		try {
			var realName = $("#realName").val();
			var phone = $("#phone").val();
			var address = $("#address").val();
			var c1 = $("#category1 option:selected");
			var c2 = $("#category2 option:selected");
			var c3 = $("#category3 option:selected");
			var pid = c1.attr("data-id");
			var cid = c2.attr("data-id");
			var aid = c3.attr("data-id");
			if(!realName){
				General.alert("请输入收货人姓名");
				return;
			}
			if(!phone){
				General.alert("请输入手机号码");
				return;
			}
			if(pid=="0"){
				General.alert("请选择省份");
				return;
			}
			if(cid=="0"){
				General.alert("请选择城市");
				return;
			}
			if(aid=="0"){
				General.alert("请选择区域");
				return;
			}
			if(!address){
				General.alert("请输入详细地址");
				return;
			}
			var province = c1.attr("value");
			var city = c2.attr("value");
			var area = c3.attr("value");
			var type = $("#addressType").val();
			var data = {
				type: type,
				name: realName,
				phone: phone,
				province: province,
				city: city,
				address: address,
				area: area
			};
			if (type == "edit") {
				data["id"] = $("#addressId").val();
			}
			var url = $(this).attr("data-href"); //保存的地址
			var tip = "正在保存地址"
			var isHideLoading = false;
			var successFun = saveResult;
			//			var params=province+city+area+address;
			var params = data;
			var isHideResponse = true; //不弹出结果
			Common.ajaxPostWantResult(url, data, tip, null, null, isHideLoading, successFun, params, isHideResponse);
		} catch (e) {}
	});
	//保存成功后执行的操作
	function saveResult(data) {
//		console.log(data);
		try {
			var id = data["id"]; //服务器返回的id
			$("#defaultAdressContainer").removeClass("hide");
			$("#adressContainer").addClass("hide");
			$("#addressId").val(id);
			var params = data["successParam"];
			$("#defaultName").html(params["name"]);
			$("#defaultPhone").html(params["phone"]);
			var address = params["province"] + params["city"] + params["area"] + params["address"];
			$("#defaultAddress").html(address);
		} catch (e) {
		}
	};
	//-----------------点击编辑地址按钮-----------------
	$("#editAddress").on("click", function() {
		try {
			$("#defaultAdressContainer").addClass("hide");
			$("#adressContainer").removeClass("hide");
			$("#addressType").val("edit");
		} catch (e) {}
	});
	//-----------------省市区关联操作-----------------
	initCategory();
	//初始化一级分类
	function initCategory() {
		//根据一级分类切换二级分类
		$("#category1").on("change", function(e) {
			changeCategory();
		});
		//根据二级分类切换三级分类
		$("#category2").on("change", function(e) {
			changeCategory2();
		});
	};
	//根据一级分类切换二级分类
	function changeCategory() {
		var id = $("#category1 option:selected").attr("data-id");
		var str = '';
		str += '<option value="' + levelTip2 + '" data-id="' + idNotSelect + '" selected>' + levelTip2 + '</option>';
		$("#category2").html(str);
		var str3 = '<option value="' + levelTip3 + '" data-id="' + idNotSelect + '" selected>' + levelTip3 + '</option>';
		$("#category3").html(str3);
		if (id !== "0") {
			$("#category2,#category3").prop("disabled", "disabled");
			var url = addressDataUrl + "?type=city&id=" + id;
			//加载市
			$.ajax({
				type: "GET",
				url: url,
				cache: false,
				dataType: 'jsonp',
				success: function(data) {
					try {
						$.each(data.city, function(key, value) {
							str += '<option value="' + value + '" data-id="' + key + '">' + value + '</option>';
							$("#category2").html(str).prop("disabled", false);
						});
					} catch (e) {}
				},
				error: function() {
					try {
						General.alert("获取市失败,请检查网络连接");
					} catch (e) {}
				}
			});
		} else {

		}
	};
	//根据二级分类切换三级分类
	function changeCategory2() {
		var id = $("#category2 option:selected").attr("data-id");
		var str = '';
		str += '<option value="' + levelTip3 + '" data-id="' + idNotSelect + '" selected>' + levelTip3 + '</option>';
		$("#category3").html(str);
		if (id !== "0") {
			$("#category3").prop("disabled", "disabled");
			var url = addressDataUrl + "?type=area&id=" + id;
			//加载市
			$.ajax({
				type: "GET",
				url: url,
				cache: false,
				dataType: 'jsonp',
				success: function(data) {
					try {
						$.each(data.area, function(key, value) {
							str += '<option value="' + value + '" data-id="' + key + '">' + value + '</option>';
							$("#category3").html(str).prop("disabled", false);
						});
					} catch (e) {}
				},
				error: function() {
					try {
						General.alert("获取区域失败,请检查网络连接");
					} catch (e) {}
				}
			});
		} else {

		}
	}


	//-----------------限制只能输入数字-----------------
	var commonCheckStr = "input[type=text]"; //检查的字符串
	var eventName = 'keyup blur paste';

	$("input[data-id='count']").delegate(null, eventName, function(e) {
		if (e.type == "focusout" || e.type == "paste") {
			checkIsNumber($(e.target), true); //检查输入值是否为数字
		} else {
			checkIsNumber($(e.target)); //检查输入值是否为数字
		}
	});


	/**
	 * 检查输入值是否为数字
	 * @param {String} element 目标元素
	 * @param {Boolean} checkValid 检查数字是否有效
	 */
	function checkIsNumber(element, checkValid) {
		var value = element.val().replace(/[^0123456789]/g, '');
		if (value == "") {
			value = 1;
		}
		if (checkValid) {
			var re = /^[1-9]\d*|^[1-9]\d*\d*|0\d*[1-9]\d*$/; //非负整数							
			if (!re.test(value) && value != "") {
				$(element).val(1);
			} else {
				element.val(value);
			}
		} else {
			element.val(value);
		}
	};


	//-----------------计算总价-----------------
	//保留两位小数
	function toFixed2(num) {


	};
	//计算总价
	function countTotal() {
		try {
			var total = 0;
			$(".price-container").each(function() {
				var currentPrice = $(this).find(".price").html();
				var currentCount = $(this).find(".quantity").html();
				currentCount = parseInt(currentCount);
				if (isNaN(currentCount)) {
					currentCount = 0;
				}
				currentPrice = parseFloat(currentPrice);
				if (isNaN(currentPrice)) {
					currentPrice = 0;
				}
				currentPrice *= currentCount;
				total += currentPrice;
			});
			total = Math.round(total * 100) / 100;
			$("#totalMoney").html(total);
		} catch (e) {}
	};
	//计算总价
	function countCurrentTotal(countElement) {
		try {
			//获取当前价格
			var currentCount = countElement.val();
			var gItem = countElement.closest(".g-item");
			var priceItem = countElement.parent().siblings(".price-container").find(".price");
			priceItem.siblings(".quantity").html(currentCount);
			countTotal();
		} catch (e) {}
	};
	$("button[data-id='plus']").on("click", function() {
		var result = 1;
		try {
			var countElement = $(this).closest(".input-group").find("input[data-id='count']");
			var c = countElement.val();
			c = parseInt(c);
			if (isNaN(c)) {
				c = 0;
			}
			result = c;
			result++;
			countElement.val(result);
			countCurrentTotal(countElement); //计算总价
		} catch (e) {}
	});
	$("button[data-id='minus']").on("click", function() {
		var result = 1;
		try {
			var countElement = $(this).closest(".input-group").find("input[data-id='count']");
			var c = countElement.val();
			c = parseInt(c);
			if (isNaN(c)) {
				c = 0;
			}
			result = c;
			result--;
			if (result < 1)
				result = 1;
			countElement.val(result);
			countCurrentTotal(countElement); //计算总价
		} catch (e) {}
	});

	//-----------------删除商品-----------------
	//	$("#cartList .delete-icon").on("click", function(e) {
	//		General.stopEvent(e);
	//		var url = $(this).attr("href");
	//		General.confirm("您确定要删除该商品吗?", null, goto, null, url);
	//	});
	//
	//	function goto(url) {
	//		window.location.href = url;
	//	};

	//-----------------微信支付-----------------
	$("#payButton:not('.disable')").on("click", function(e) {
		General.stopEvent(e);
		//判断是否有收货地址
		var addressId = $("#addressId").val();
		if (addressId) {
			var isCheckProduct = $("#isAgree").prop("checked");
			if (isCheckProduct) {
				$("#buyForm").submit();
			} else {
				General.alert("请先同意本公司的购买条款");
			}
		} else {
			General.alert("请先保存收货地址");
		}
	});
});